const router = require('koa-router')()
const utlis = require('../utlis/common')
const {Menu} = require('../models/menuSchema')
router.prefix('/menus')

router.get('/list',async ctx=>{
  const { menuName,menuState } = ctx.request.query
  const params={}
  if(menuName)params.menuName=menuName
  if(menuState)params.menuState=menuState
  let rootList =await Menu.find(params) || []
  const permissionList = getTreeMenu(rootList,null,[])
  ctx.body=utlis.success(permissionList)
})

function getTreeMenu(rootList,id,list){
   for(let i=0;i<rootList.length;i++){
     let item = rootList[i]
     if(String(item.parentId.slice().pop()) == String(id)){
        list.push(item._doc)
     }
   }
   list.map(item=>{
     item['children'] = []
     getTreeMenu(rootList,item._id,item.children)
     if(item.children.length == 0){
       delete item.children
     }else if(item.children.length>0 && item.children[0].menuType ==2) {
       //快速区分按钮和菜单
       item.action =item.children
     }
   })
   return list
}


router.post('/menuoperate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info
  try {
    if (action === 'add') {
      res = await Menu.create(params)
      ctx.body={
        code:200,
        msg:'添加成功',
        data:'ok'
      }
      info = '创建成功'
    } else if (action == 'edit') {
      params.updateTime=new Date()
      res = await Menu.findByIdAndUpdate(_id,params)
      ctx.body={
        code:200,
        msg:'更新成功',
        data:'ok'
      }
      info = '编辑成功'
    } else {
      res = await Menu.findByIdAndRemove(_id)
      await Menu.deleteMany({parentId:{$all:[_id]}})
      ctx.body={
        code:200,
        msg:'删除成功',
        data:'ok'
      }
      info = '删除成功'
    }
    ctx.body=utlis.success('',info)
  } catch (error) {
    utlis.fail(error.stack)
  }
})

module.exports = router